package com.jian.java;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * @author Jiange
 * @create 2021-05-10-14:16
 */
public class JedisDemo {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.48.131", 6379);
        String ping = jedis.ping();
        System.out.println(ping);
    }

    @Test
    public void test1(){
        Jedis jedis = new Jedis("192.168.48.131", 6379);

        jedis.set("k2","value2");

        System.out.println(jedis.get("k1"));

        Set<String> keys = jedis.keys("*");
        keys.forEach(e->{
            System.out.println(e);
        });
    }

    @Test
    public void test2(){
        Jedis jedis = new Jedis("192.168.48.131", 6379);

        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            int i1 = random.nextInt(10);
            code += i1;
        }

        String count = "count"+code;
        String s = jedis.get(count);

        if(s == null){
            jedis.setex(count,24*60*60,"1");
        }else if(Integer.parseInt(count)<=2){
            jedis.incr(count);
        }else {
            jedis.close();
        }
    }

    public static boolean doSecKill(String uid,String prodid){
        if(uid ==null || prodid == null){
            return false;
        }
        Jedis jedis = new Jedis("a", 12);

        //库存key
        String KC_Key = "sk"+prodid;

        //秒杀的用户的key
        String userKey = "sk"+prodid;
        Transaction multi = jedis.multi();

        //判断库存是否为空
        String kc = jedis.get(KC_Key);
        if(kc == null){
            System.out.println("没货");
            return false;
        }
        Boolean sismember = jedis.sismember(userKey, uid);
        if(sismember){
            System.out.println("不能重复秒杀");
            jedis.close();
            return false;
        }
        if(Integer.parseInt(kc) == 0){
            System.out.println("没货了");
        }
        multi.decr(KC_Key);
        multi.sadd(userKey,uid);

        List<Object> exec = multi.exec();
        if(exec.size() == 0 ||exec ==null){
            return false;
        }

        return true;
    }
}
